import redis from "redis";
export default class Redis {
  constructor({ prot, host, password, database }) {
    try {
      // 获取配置
      let redisClient = redis.createClient(prot || 6379, host);
      redisClient.auth(password || "");
      redisClient.select(database || 1, (err) => { })
      redisClient.on("connect", function () {
        console.log(`Redis Prot ${prot || 6379} =>连接成功${new Date()}`);
      });
      redisClient.on("error", function (err) {
        console.log("Redis error: " + err);
      });
      this.client = redisClient;
    } catch (error) {
      console.error(error);
    }
  }
  async get(key) {
    const data = await new Promise((resolve) => {
      this.client.get(key, function (err, res) {
        return resolve(res || "");
      });
    });
    ((key.indexOf("client_") !== -1) && !data) && console.error(`未获取到key为=>${key}${new Date()}`)
    return data.deJson();
  }
  async set(name, value, time = 0) {
    await new Promise((resolve) => {
      this.client.ttl(name, function (r, b) {
        if (b !== -1 && b >= 0) (time = time || b);//如果不等于-1则续上之前得时间
        resolve(true);
      })
    })
    const data = await new Promise((resolve) => {
      this.client.set(name, value, function (err, res) {
        return resolve(res || "");
      });
    });
    time && this.client.expire(name, time);//设置过期时间
    return data
  }
  del(name) {
    return this.client.del(name);
  }
  // 添加到list末位
  async zadd(hname, value) {
    const data = await new Promise((resolve) => {
      this.client.zadd(hname, +new Date(), value, function (err, res) {
        resolve(res);
      });
    });
    return data;
  }
  //获取总长
  async zcard(hname) {
    const data = await new Promise((resolve) => {
      this.client.zcard(hname, function (err, res) {
        resolve(res);
      });
    });
    return data;
  }
  //获取第一个元素
  async zrange(hname) {
    const data = await new Promise((resolve) => {
      this.client.zrange(hname, 0, 0, function (err, [res]) {
        resolve(res || null);
      });
    });
    return data;
  }
  //移出指定元素
  async zrem(hname, info) {
    const data = await new Promise((resolve) => {
      this.client.zrem(hname, info, function (err, res) {
        resolve(res);
      });
    });
    return data;
  }
}
